import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:management/model/gate_model.dart';
import 'package:management/model/msc_model.dart';
import 'package:management/utils/log_utils.dart';
import 'package:management/views/gate/gate_page_content.dart';

///闸门管理
class GatePage extends StatefulWidget {
  @override
  _GatePageState createState() => _GatePageState();
}

class _GatePageState extends State<GatePage> {
  late List<GateModel> gateData;


  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIOverlays([]);
    // queryGateList();
  }

  _buildAppBar() => AppBar(
        title: Text(
          "闸门",
          style: TextStyle(
              color: Colors.black, fontWeight: FontWeight.bold, fontSize: 25),
        ),
        centerTitle: true,
        backgroundColor: Colors.yellow,
        actions: [
          Theme(
              data: ThemeData(cardColor: Colors.black),
              child: PopupMenuButton(
                iconSize: 35,
                itemBuilder: (context) => [
                  PopupMenuItem(
                    child: Wrap(
                      spacing: 10,
                      children: [
                        Icon(
                          Icons.done_all,
                          color: Colors.yellow,
                        ),
                        Text(
                          "开启所有",
                          style: TextStyle(color: Colors.white, fontSize: 25),
                        ),
                      ],
                    ),
                    value: "开启所有",
                  ),
                ],
                onSelected: (v) {
                  if (gateData == null) {
                    return;
                  }
                  if (gateData.isEmpty) {
                    return;
                  }

                  gateData.forEach((element) async {
                    if (element.departmentId == "0") {
                      element.openLPRGate(element.deviceId);
                    } else {
                      element.openFaceGate(showFailToast: true);
                    }
                  });
                },
                onCanceled: () {
                  MyLog.d("onCanceled");
                },
              ))
        ],
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(),
      body: FutureBuilder(
        future: GateProvider.instance.getAllGate(),
        builder: (context, snap) {
          if (snap.hasData) {
            gateData = snap.data as List<GateModel>;
            // gateData.forEach((element) {
            //   MyLog.i(element.toMap().toString());
            // });

            return GatePageContent(

              gateList: snap.data as List<GateModel>,
              onLongPress: (index) {
                if (SpUtil.getString("userName") == "admin") {
                  showDialog(
                    context: context,
                    builder: (context) => AlertDialog(
                      title: Text("提示"),
                      content: Text(
                        "要删除设备吗？",
                        style: TextStyle(color: Colors.red),
                      ),
                      actions: [
                        TextButton(
                          onPressed: () {
                            GateProvider.instance
                                .delete(gateData[index].deviceName!);
                            gateData.removeAt(index);
                            setState(() {});
                            Navigator.of(context).pop();
                          },
                          child: Text("确认"),
                        ),
                        TextButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: Text("取消"),
                        ),
                      ],
                    ),
                  );
                }
              },
              onEdit: () => setState(() {}),

            );
          }
          return Center(
            child: FutureBuilder(
              future: Future.delayed(Duration(seconds: 3)),
              builder: (context, snap) {
                if (snap.connectionState == ConnectionState.done) {
                  return Text("还没有闸门");
                } else {
                  return CircularProgressIndicator();
                }
              },
            ),
          );
        },
      ),
      bottomSheet: Container(
        padding: EdgeInsets.only(bottom: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.warning_amber_sharp,
              color: Colors.deepOrange,
            ),
            Text(
              "开闸时注意检查通行安全",
              style: TextStyle(color: Colors.deepOrange, fontSize: 18),
            ),
          ],
        ),
      ),
      // floatingActionButton: _buildFloatingActionButton(),
    );
  }

  //查询闸门数据
  void queryGateList() async {
    List<GateModel>? gates = await GateProvider.instance.getAllGate();
    if (gates == null) {
      return;
    }
    setState(() {
      gateData = gates;
    });
    MyLog.i("闸门数据：${gates.length}");
  }

  @override
  void dispose() {
    final BasicMessageChannel mscChannel =
        BasicMessageChannel("MscChannel", StandardMessageCodec());
    mscChannel.send(MscChannelModel(message: {"cmd": "dispose"}).toMap());
    super.dispose();
  }
}
